import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, Input, DatePicker, Modal } from "antd";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import {
  PlusOutlined,
  EditOutlined,
  DownloadOutlined,
  SearchOutlined,
  RedoOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  format_time,
  add_zero,
  fenToyuan,
} from "../../utils";
import axios from "../../axios/index";

export default function MoneySubmit(props) {
  dayjs.extend(customParseFormat);
  const { t } = useTranslation();
  const { RangePicker } = DatePicker;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  let today_time = new Date();
  let year = today_time.getFullYear();
  let month = add_zero(today_time.getMonth() + 1);
  let day = today_time.getDate();
  const [search_date_stamp, setSearch_date_stamp] = useState(
    new Date(year, month, day)
  );
  const [leftData, setLeftData] = useState([]);
  const [leftPage, setLeftPage] = useState(1);
  const [leftRows, setLeftRows] = useState(20);
  const [leftTotal, setLeftTotal] = useState(0);
  const getLeftData = async (newPage, newRows) => {
    let upMsg = {
      pageNum: newPage ? newPage : leftPage,
      pageSize: newRows ? newRows : leftRows,
      bizUserId: username,
      request_type: "findwithdrawal",
    };
    setSpinning(true);
    let res = await post_axios("union_pay", "union_pay", upMsg);
    setSpinning(false);
    if (!res) return;
    setLeftData(res.data.BusinessUser);
    setLeftTotal(res.data.Total);
  };
  const leftColumns = [
    {
      title: "公司名称",
      dataIndex: "companyName",
      align: "center",
    },
    {
      title: "银行卡属性",
      align: "center",
      render: (_, record) => (
        <>
          {record.bankCardPro == 0 ? (
            <span>个人银行卡</span>
          ) : (
            <span>企业对公账户</span>
          )}
        </>
      ),
    },
    {
      title: "提现金额(元)",
      dataIndex: "amount",
      align: "center",
    },
    {
      title: "提现状态",
      align: "center",
      render: (_, record) => (
        <>
          {record.status === 0 ? (
            <span>待审核</span>
          ) : record.status === 1 ? (
            <span>提现失败</span>
          ) : (
            <span>提现成功</span>
          )}
        </>
      ),
    },
    {
      title: "提交签订时间",
      dataIndex: "time",
      align: "center",
    },
  ];
  // 分页器
  const leftPageOnChange = async (page, pageSize) => {
    setLeftPage(page);
    setLeftRows(pageSize);
    getLeftData(page, pageSize);
  };

  const search_data = () => {
    setLeftPage(1);
    getLeftData(1);
  };

  const [daily_page, setDaily_page] = useState(1);
  const [daily_rows, setDaily_rows] = useState(20);
  const [daily_total, setDaily_total] = useState(0);
  const [daily_list, setDaily_list] = useState([]);
  // 分页查询每日会员账户收益
  const get_daily_data = async () => {
    let upMsg = {
      pageNum: daily_page,
      pageSize: daily_rows,
      bizUserId: username,
      request_type: "findDailyAmount",
    };
    let res = await post_axios("union_pay", "union_pay", upMsg);
    if (!res) return;
    setDaily_list(res.data.BusinessUser);
    setDaily_total(res.data.Total);
  };
  const rightColumns = [
    {
      title: "公司名称",
      dataIndex: "companyName",
      align: "center",
    },
    {
      title: "日期",
      dataIndex: "date",
      align: "center",
    },
    {
      title: "当天起始金额(元)",
      align: "center",
      render: (_, record) => (
        <>
          <div>{fenToyuan(record.startingAmount)}</div>
        </>
      ),
    },
    {
      title: "当天结束金额(元)",
      align: "center",
      render: (_, record) => (
        <>
          <div>{fenToyuan(record.endAmount)}</div>
        </>
      ),
    },
  ];
  // 分页器
  const rightPageOnChange = async (page, pageSize) => {
    setDaily_page(page);
    setDaily_rows(pageSize);
    get_daily_data(page, pageSize);
  };

  const daily_search_list = () => {
    setDaily_page(1);
    get_daily_data(1);
  };

  // 查询余额
  const [add_submit_reflect_show, setAdd_submit_reflect_show] = useState(false);
  const [acount_balance, setAcount_balance] = useState("0");
  const query_acount_balance = async () => {
    let upMsg = {
      request_type: "balance",
      bizUserId: username,
    };
    let res = await post_axios("union_pay", "union_pay", upMsg);
    if (!res) return;
    let balance = `${Math.round(res.data.allAmount)}`;
    setAcount_balance(fenToyuan(balance));
  };
  const submit_reflect = async () => {
    setSubmit_obj({
      amount: 0,
      bankCardPro: "",
    });
    setAdd_submit_reflect_show(true);
  };

  const [submit_obj, setSubmit_obj] = useState({
    amount: 0,
    bankCardPro: "",
  });

  const submit_reflect_onChange = (value, key) => {
    let newObj = JSON.parse(JSON.stringify(submit_obj));
    newObj[key] = value;
    setSubmit_obj(newObj);
  };
  const add_submit_reflect_confirm = async () => {
    let upMsg = Object.assign(
      {
        request_type: "addWithdrawal",
        bizUserId: username,
      },
      submit_obj
    );
    setSpinning(true);
    let res = await post_axios("union_pay", "union_pay", upMsg);
    setSpinning(false);
    if (!res) return;
    setAdd_submit_reflect_show(false);
    getLeftData();
    query_acount_balance();
  };

  // 商户集合对账文件下载
  const [date_stamp, setDate_stamp] = useState(new Date(year, month, day));
  const [fileType, setFileType] = useState("");
  const [download_show, setDownload_show] = useState(false);
  const download_show_click = () => {
    setDownload_show(true);
  };
  const download_show_confirm = async () => {
    const newDate = format_time(new Date(date_stamp), "time_date").replaceAll(
      "-",
      ""
    );
    let upMsg = {
      request_type: "download",
      date: newDate,
      fileType: fileType,
    };
    let res = await post_axios("union_pay", "union_pay", upMsg);
    if (!res) return;
    if (res.data.url) {
      window.location.href = res.data.url;
    } else {
      alert("url格式错误");
    }
  };

  const export_data = async () => {
    setSpinning(true);
    let upMsg = {
      request_type: "export",
      bizUserId: username,
      dateTime: format_time(new Date(search_date_stamp), "time_date"),
    };
    axios
      .post("/mega/download", upMsg, {
        responseType: "blob",
      })
      .then((res) => {
        console.log(res);
        setSpinning(false);
        const url = window.URL.createObjectURL(res.data);
        const a = document.createElement("a");
        a.href = url;
        a.download = "分账明细表.xls";
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
      })
      .catch((err) => {
        setSpinning(false);
        console.log(err);
      });
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getLeftData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("money_submit")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
    get_daily_data();
    query_acount_balance();
  }, []);
  return (
    <>
      <div className="money_submit modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div className="ipt_box_title">{t("system_manager.time")}</div>
            <DatePicker
              size="small"
              onChange={(date, dateString) => {
                setDate_stamp(date);
              }}
            />
          </div>
          <div className="ipt_box">
            <div
              className="ipt_box_title"
              style={{
                color: "blue",
                fontSize: "18px",
              }}
            >
              可用余额:{acount_balance}元
            </div>
            <Button
              shape="circle"
              icon={<RedoOutlined />}
              onClick={query_acount_balance}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box" style={{ width: "50vw" }}>
            {/* 添加 */}
            {menu_action.indexOf("m_submit") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={submit_reflect}
              >
                {text_check(user_power_lang["m_submit"])}
              </Button>
            ) : (
              ""
            )}
            {/* 账单下载 */}
            {menu_action.indexOf("m_down_bill") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DownloadOutlined style={{ color: "#1677FF" }} />}
                onClick={download_show_click}
              >
                {text_check(user_power_lang["m_down_bill"])}
              </Button>
            ) : (
              ""
            )}
            {/* 分账明细 */}
            {menu_action.indexOf("m_down_bill_detail") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DownloadOutlined style={{ color: "#1677FF" }} />}
                onClick={export_data}
              >
                {text_check(user_power_lang["m_down_bill_detail"])}
              </Button>
            ) : (
              ""
            )}
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={search_data}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          </div>
          <div className="btn_box" style={{ width: "50vw" }}>
            {/* 查询 */}
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={daily_search_list}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          </div>
        </div>
        <div className="table_box">
          <div className="page-table" style={{ width: "50vw" }}>
            <Table
              dataSource={leftData}
              size="small"
              bordered
              columns={leftColumns}
              rowKey="id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              pagination={{
                defaultCurrent: leftPage,
                defaultPageSize: leftRows,
                size: "small",
                current: leftPage,
                total: leftTotal,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: leftPageOnChange,
              }}
            />
          </div>
          <div className="page-table" style={{ width: "50vw" }}>
            <Table
              dataSource={daily_list}
              size="small"
              bordered
              columns={rightColumns}
              rowKey="id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              pagination={{
                defaultCurrent: daily_page,
                defaultPageSize: daily_rows,
                size: "small",
                current: daily_page,
                total: daily_total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: rightPageOnChange,
              }}
            />
          </div>
        </div>
      </div>
      <Modal
        title="申请提现"
        open={add_submit_reflect_show}
        onOk={add_submit_reflect_confirm}
        onCancel={() => setAdd_submit_reflect_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">订单金额</div>
          <Input
            placeholder=" "
            value={submit_obj.amount}
            onChange={(e) => submit_reflect_onChange(e.target.value, "amount")}
          />
        </div>
        <p style={{ color: "red", margin: "-10px 0" }}>
          * 提现银行卡为注册绑定的银行卡
        </p>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">账户属性</div>
          <Select
            placeholder=" "
            options={[
              {
                label: "个人银行卡",
                value: "0",
              },
              {
                label: "企业对公账户",
                value: "1",
              },
            ]}
            value={submit_obj.bankCardPro}
            onChange={(value) => submit_reflect_onChange(value, "bankCardPro")}
          />
        </div>
      </Modal>

      <Modal
        title="对账文件下载"
        open={download_show}
        onOk={download_show_confirm}
        onCancel={() => setDownload_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">对账文件日期</div>
          <DatePicker
            onChange={(date, dateString) => {
              setDate_stamp(date);
            }}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">文件类型</div>
          <Select
            placeholder=" "
            options={[
              {
                label: "明细",
                value: "1",
              },
              {
                label: "汇总",
                value: "2",
              },
              {
                label: "excel对账单（含汇总及明细,文件上盖有清结算章）",
                value: "3",
              },
            ]}
            value={fileType}
            onChange={(value) => setFileType(value)}
          />
        </div>
      </Modal>
    </>
  );
}
